
/*
 * GET home page.
 */
var crypto = require('crypto');
var User = require('../modules/user.js');

module.exports = function(app) {
  app.get('/', function(req,res) {
  	res.render('index', { title: 'Express' });

  });
  app.get('/reg',checkNotLogin);
  app.get('/reg', function(req,res){
    res.render('reg',{title: 'Reg'});    
  });
  app.post('/reg',checkNotLogin);
  app.post('/reg',function(req,res){
      if(req.body['password'] != req.body['password-repeat']){
          req.flash('error','password mismatch');
          return res.redirect('/reg');
      }
      User.findOne({'username':req.body.username},'username',function(err,iuser){
          if(iuser){
			  console.log(iuser);
              req.flash('error','User exists');
              return res.redirect('/login');
          }
          var user = new User();
          user.username = req.body.username;
          var md5 = crypto.createHash('md5');
          user.password = md5.update(req.body.password).digest('base64');
          user.email = req.body.email;
          console.log(user);
          user.save(function(err){
              if(err){
                  req.flash('error',err);
                  return res.redirect('/reg');
              }
			  req.session.user = user;
			  req.flash('success','Reg success');
			  //reg success
			  //redirect to the edit page to fullfill the user's contact info
			  //for reserving the conference
              res.redirect('/u/'+req.body.username+'/edit');
          });
      });
  });

  app.post('/login',checkNotLogin);
  app.post('/login',function(req,res){
      var md5 = crypto.createHash('md5');
      var password = md5.update(req.body.password).digest('base64');
      console.log(req.body.password);
      User.findOne({'username':req.body.username},'username password',function(err,iuser){
          if(!iuser){
              req.flash('error','User not exists');
              return res.redirect('/reg');
          }
          if( iuser.password != password ){
              req.flash('error','Password Wrong!');
              return res.redirect('/');
          }
		  console.log(iuser);
          req.session.user = iuser;
          req.flash('success','Login success');
          res.redirect("/");
      });
  });

  app.get('/logout',checkLogin);
  app.get('/logout',function(req,res){
  	req.session.user = null;
  	req.flash('success','logout');
  	res.redirect('/');
  });

  app.get('/u/:user/edit',checkLogin);
  app.get('/u/:user/edit',function(req,res){
	res.redirect('/');
  });

  function checkNotLogin(req,res,next){
	if(req.session.user){
		req.flash('error','Already loged in');
		return res.redirect('/');
	}
	next();
  }
  function checkLogin(req,res,next){
  	if(!req.session.user){
		req.flash('error','Not log in.');
		return res.redirect('/');
	}
  	next();
  }
  return app.router;
};
